package hn.cch.security.configuration;

import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author CCH
 * @version 2018.09.21
 */
public class CsrfProtectionMatcher implements RequestMatcher {

    private List<String> execludePaths;
    private Pattern allowedMethods;

    public CsrfProtectionMatcher() {
        this.execludePaths = new ArrayList<>();
        execludePaths.add("/execlude/");
        this.allowedMethods = Pattern.compile("^(GET|POST)$");
    }

    @Override
    public boolean matches(HttpServletRequest httpServletRequest) {

        String servletPath = httpServletRequest.getServletPath();
        for (String path : execludePaths) {
            if (servletPath.contains(path)) {
                return false;
            }
        }

        return !allowedMethods.matcher(httpServletRequest.getMethod()).matches();
    }
}
